import { getUser } from "@/lib/authUtils";
import OpenAI from "openai";
import type { ChatCompletionMessageParam } from "openai/resources/index.mjs";
import { match } from "ts-pattern";
import { NextResponse } from 'next/server';
import prisma from "@/lib/prisma";
// Create an OpenAI API client (that's edge friendly!)

// IMPORTANT! Set the runtime to edge: https://vercel.com/docs/functions/edge-functions/edge-runtime
// export const runtime = "edge";

export async function POST(req: Request): Promise<Response> {
  const userid = await getUser(req)
  if (!userid || userid instanceof NextResponse) {
    return NextResponse.json(
      { error: '未授权或登录信息过期，请登录' },
      { status: 401 }
    )
  }
  await prisma.vms_user.update({
    where: { id: userid },
    data: {
      ai_count: {
        increment: 1
      }
    }
  })
  
  
  const openai = new OpenAI({
    apiKey: process.env.OPENAI_API_KEY,
    baseURL: process.env.OPENAI_BASE_URL,
  });
  // Check if the OPENAI_API_KEY is set, if not return 400
  if (!process.env.OPENAI_API_KEY || process.env.OPENAI_API_KEY === "") {
    return new Response("Missing OPENAI_API_KEY - make sure to add it to your .env file.", {
      status: 400,
    });
  }

  const { prompt, option, command } = await req.json();
  // const messages = match(option)
  //   .with("continue", () => [
  //     {
  //       role: "system",
  //       content:
  //         "You are an AI writing assistant that continues existing text based on context from prior text. " +
  //         "Give more weight/priority to the later characters than the beginning ones. " +
  //         "Limit your response to no more than 200 characters, but make sure to construct complete sentences." +
  //         "Use Markdown formatting when appropriate.",
  //     },
  //     {
  //       role: "user",
  //       content: prompt,
  //     },
  //   ])
  //   .with("improve", () => [
  //     {
  //       role: "system",
  //       content:
  //         "You are an AI writing assistant that improves existing text. " +
  //         "Limit your response to no more than 200 characters, but make sure to construct complete sentences." +
  //         "Use Markdown formatting when appropriate.",
  //     },
  //     {
  //       role: "user",
  //       content: `The existing text is: ${prompt}`,
  //     },
  //   ])
  //   .with("shorter", () => [
  //     {
  //       role: "system",
  //       content:
  //         "You are an AI writing assistant that shortens existing text. " + "Use Markdown formatting when appropriate.",
  //     },
  //     {
  //       role: "user",
  //       content: `The existing text is: ${prompt}`,
  //     },
  //   ])
  //   .with("longer", () => [
  //     {
  //       role: "system",
  //       content:
  //         "You are an AI writing assistant that lengthens existing text. " +
  //         "Use Markdown formatting when appropriate.",
  //     },
  //     {
  //       role: "user",
  //       content: `The existing text is: ${prompt}`,
  //     },
  //   ])
  //   .with("fix", () => [
  //     {
  //       role: "system",
  //       content:
  //         "You are an AI writing assistant that fixes grammar and spelling errors in existing text. " +
  //         "Limit your response to no more than 200 characters, but make sure to construct complete sentences." +
  //         "Use Markdown formatting when appropriate.",
  //     },
  //     {
  //       role: "user",
  //       content: `The existing text is: ${prompt}`,
  //     },
  //   ])
  //   .with("zap", () => [
  //     {
  //       role: "system",
  //       content:
  //         "You area an AI writing assistant that generates text based on a prompt. " +
  //         "You take an input from the user and a command for manipulating the text" +
  //         "Use Markdown formatting when appropriate.",
  //     },
  //     {
  //       role: "user",
  //       content: `For this text: ${prompt}. You have to respect the command: ${command}`,
  //     },
  //   ])
  //   .run() as ChatCompletionMessageParam[];


const BASE_ROLE = "你是youtube视频博主，拥有百万粉丝账号操盘经验.";
const COMMON_REQUIREMENTS = 
  "◆ 始终使用口语化表达\n" +
  "◆ 采用「悬念前置+信息密度」结构\n" +
  "◆ 每15秒设置一个剧情钩子\n";

  const messages = match(option)
  .with("generate", () => [
    {
      role: "system",
      content:BASE_ROLE+
      "根据现有内容写一篇完整的文案\n" +
      "▼ 核心要求\n" +
      "● 首行必须生成3个爆款标题选项（emoji+数字标题）\n" +
      "● 后半段优先安排转化触发点\n" +
      "● 结尾预留互动话术接口\n" 
      // COMMON_REQUIREMENTS
    },
    {
      role: "user",
      content: prompt,
    },
  ])
  .with("improve", () => [
    {
      role: "system",
      content:
      BASE_ROLE+
      "根据输入的文稿进行文本润色，要求文本正式，内容精简严肃，抓住用户痛点吸引用户观看，只返回处理后的文稿。"
    },
    {
      role: "user",
      content: `现有文本是：${prompt}`,
    },
  ])
  .with("shorter", () => [
    {
      role: "system",
      content:
      BASE_ROLE+
     "根据输入的文稿进行高质量文本摘要，只返回处理后内容。"
    },
    {
      role: "user",
      content: `现有文本是：${prompt}`,
    },
  ])
  .with("longer", () => [
    {
      role: "system",
      content:
      BASE_ROLE+
      "根据输入的文稿进行文本续写，要求文本正式，内容精简严肃，只返回续写的内容。"
    },
    {
      role: "user",
      content: `现有文本是：${prompt}`,
    },
  ])
  .with("fix", () => [
    {
      role: "system",
      content:
      BASE_ROLE + "润色文案,修复语法和拼写错误，返回需要修改语法和拼写的点，无需返回完整文本\n" 
    },
    {
      role: "user",
      content: `现有文本是：${prompt}`,
    },
  ])
  .with("zap", () => [
    {
      role: "system",
      content:
      BASE_ROLE +
        "根据输入的文稿和要求进行文本修改" +
        "在适当的时候使用Markdown格式。",
    },
    {
      role: "user",
      content: `对于这段文本：${prompt}。你必须遵守这些要求：${command}`,
    },
  ])
  .run() as ChatCompletionMessageParam[];


  const response = await openai.chat.completions.create({
    model: "deepseek-chat",
    stream: true,
    temperature: 1.2,
    messages,
  });

// Create a ReadableStream from the OpenAI response
const stream = new ReadableStream({
  async start(controller) {
    const encoder = new TextEncoder();
    
    for await (const chunk of response) {
      const content = chunk.choices[0]?.delta?.content || "";
      controller.enqueue(encoder.encode(content));
    }
    controller.close();
  },
});

// Return the stream with proper headers
return new Response(stream, {
  headers: {
    'Content-Type': 'text/plain; charset=utf-8',
    'Transfer-Encoding': 'chunked',
  },
});
}
